package ca.llsutherland.squash.dao;

import java.sql.ResultSet;
import java.sql.SQLException;

import ca.llsutherland.squash.domain.Clock;
import ca.llsutherland.squash.domain.Role;
import ca.llsutherland.squash.domain.helper.RolesHelper;
import ca.llsutherland.squash.exceptions.ValidationException;
import ca.llsutherland.squash.utils.StringUtils;


public class RolesDao extends BaseDao {

    private static RolesDao instance = new RolesDao();

    @Override
    public String getUnderlyingTableName() {
        return "ROLES";
    }

    public static RolesDao getInstance() {
        return instance ;
    }

    public Role findByName(String name) {
        String findByNameQuery = getFindByNameQuery(name);
        return buildRole(findByNameQuery);
    }

    private Role buildRole(String sql) {
        Role role = null;
        ResultSet rs = super.findByQuery(sql);
        
        try {
            if(rs.next()){
                String name = rs.getString("NAME");
                Clock dateCreated = new Clock(rs.getTimestamp("DATE_CREATED").getTime());
                Clock dateUpdated = new Clock(rs.getTimestamp("DATE_UPDATED").getTime());
                Long id = Long.valueOf(rs.getLong("ID"));
                
                role = RolesHelper.createNewRole(name, dateCreated, dateUpdated, id);
            }
            rs.close();
        } catch (SQLException e) {
            throw new ValidationException(e.getMessage() + " in buildCourtStyle()");
        } finally {
            rs = null;            
        }
        return role;
    }

    public Role create(Role role) {
        String sql = "INSERT INTO " + getUnderlyingTableName() + " (ID, NAME, DATE_CREATED, DATE_UPDATED) VALUES ("
            + role.getId() + ", "
            + StringUtils.addSingleQuotes(role.getName()) + ", "
            + StringUtils.addSingleQuotes(role.getDateCreated().toString()) + ", "
            + StringUtils.addSingleQuotes(role.getDateUpdated().toString()) + ");";
        return findById(super.create(sql));
    }

    public Role findById(Long id) {
        String findByIdQuery = getFindByIdQuery(id);
        return buildRole(findByIdQuery);
    }

}
